import React, { Component, Suspense } from 'react';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';

import { connect } from 'dva';
import PageLoading from '@/components/PageLoading';
import { FormattedMessage } from 'umi-plugin-react/locale';
import {
  Row,
  Col,
  Card,
  Icon,
  Form,
  Table,
  Modal,
  Spin,
  Button,
  message,
  Tooltip,
  Pagination,
  Switch,
} from 'antd';
import moment from 'moment';

import { routerRedux } from 'dva/router';
import del1Img from '@/assets/knowledge/del1.png';
import editImg from '@/assets/knowledge/edit.png';
import RobotBtn from '@/utils/robotBtn';
import Bottword from '@/modules/Bottword.js';
import moreImg from '@/assets/knowledge/more.png';
import styles from './index.less';
import addShare from '@/assets/knowledge/addShare.png';

const FormItem = Form.Item;
const dateFormat = 'YYYY/MM/DD';
const MyIcon = Icon.createFromIconfontCN({
  scriptUrl: '//at.alicdn.com/t/font_1131883_m18hmgbwet.js',
});
@connect(({ process, loading }) => ({
  process,
  loading: loading.effects['knowledgeBaseSharing/fetch'],
}))
class KnowledgeBaseSharing extends Component {
  constructor(props) {
    super(props);
    this.state = {
      knowledgeList: [],
      total: 0,
      page:1,
      pageSize:10
    };
  }

  // eslint-disable-next-line react/sort-comp
  fetche = () => {
    this.setState({ login: true });
    const { dispatch, currentUser } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'knowledgeBaseSharing/fetch',
        payload: { robotId: currentUser.robotId,page:this.state.page,limit:this.state.pageSize},
        callback: res => {
          console.log('列表数据', res);
          let val = res.list;
          val.map((item, index) => (item['key'] = index));
          val.map((item, index) => (item['start'] = true));
          this.setState({
            knowledgeList: val,
            login: false,
            total: res.total,
            pageSize: 10,
            page: 1,
          });
        },
      });
    });
  };

  componentDidMount() {
    this.fetche();
  }

  handleDelete = item => {
    console.log('item', item);
    const { dispatch } = this.props;
    // window.location.href = "/knowledge/knowledgeBaseSharing/Edit?name="+item.name+'&_id='+item._id;
    dispatch(
      routerRedux.push({
        pathname: '/knowledge/knowledgeBaseSharing/Edit',
        params: { id: item.id ,name:item.name},
      })
    );
  };

  handleDeletes = item => {
    console.log('item', item);
    Modal['confirm']({
      title: '删除任务',
      content: '确定删除吗？',
      okText: '删除',
      cancelText: '取消',
      onOk: () => {
        const { dispatch, currentUser } = this.props;
        this.reqRef = requestAnimationFrame(() => {
          dispatch({
            type: 'knowledgeBaseSharing/fetchd',
            payload: { sharedCategoryId: item._id },
            callback: res => {
              console.log('componentWillMount', res);
              if (res.status === true) {
                message['success']('执行成功！');
                this.fetche();
              }
              if (res.status === false) {
                message['error']('执行失败！');
              }
              this.fetche();
            },
          });
        });
      },
      onCancel() {
        console.log('onCancel');
      },
    });
  };

  onChangeA = val => {
    // 页数选择
    this.setState({
      page:val
    },()=>{
      this.fetche()
    })
  };

  onShowSizeChangeA = (current, pageSize) => {
    this.setState({
      pageSize:pageSize,
      page:current
    },()=>{
      this.fetche()
    })
  };

  enumeration = () => {
    const { dispatch } = this.props;
    dispatch(
      routerRedux.push({
        pathname: '/knowledge/knowledgeBaseSharing/add',
        params: { id: 'tcx' },
      })
    );
  };

  rktbonChange = (item, index) => {
    console.log(item, index);
    const { knowledgeList } = this.state;
    knowledgeList[index].start = !item.start;
    this.setState({ knowledgeList }, () => {
      console.log(this.state.knowledgeList);
    });
  };

  lessdata = () => {
    const columns = [
      {
        title: '用户名',
        width: 'calc(20vw)',
        dataIndex: 'nickName',
      },
      {
        title: '用户账号',
        width: '300px',
        dataIndex: 'name',
      },
      {
        title: '创建时间',
        width: 'calc(20vw)',
        dataIndex: 'createTime',
        render: dataIndex => {
          return moment(parseInt(dataIndex)).format('YYYY-MM-DD HH:mm:ss');
        },
      },
      {
        title: '操作',
        render: (text, item, index) => {
          return (
            <div>
              <div className={styles.tool}>
                <img
                  src={editImg}
                  alt="编辑"
                  style={{ marginRight: 5, cursor: 'pointer' }}
                  onClick={text => {
                    this.handleDelete(item);
                  }}
                />
                <img
                  src={del1Img}
                  alt="删除"
                  style={{ marginLeft: 10, cursor: 'pointer' }}
                  onClick={text => {
                    this.handleDeletes(item);
                  }}
                />
                <span style={{marginLeft:20,position:'relative',bottom:1}} className="zdyswer">
              </span>
              </div>
              <img src={moreImg} alt="" className={styles.more} />
            </div>
          );
        },
      },
    ];
    return (
      <Spin spinning={this.state.login}>
        <div className={styles.dabj} style={{ padding: '0px 20px' }}>
          <div className={styles.border} style={{ position: 'relative', right: '2px' }}>
            <Table
              className="zdyTable"
              columns={columns}
              dataSource={this.state.knowledgeList} //数据
              onChange={this.handleChange}
              pagination={false}
              pagination={false}
            />
          </div>
          <Pagination
            style={{ textAlign: 'center', marginTop: 20 }}
            total={this.state.total}
            pageSize={this.state.pageSize} // 显示几条一页
            current={this.state.page} // 当前页
            showSizeChanger={true} // 是否显示可以设置几条一页的选项
            onChange={this.onChangeA}
            onShowSizeChange={this.onShowSizeChangeA}
            showTotal={() => `共 ${this.state.total} 条`}
          />
        </div>
      </Spin>
    );
  };

  render() {
    return (
      <Suspense fallback={<PageLoading />}>
        <div style={{ margin: '10px 0px' }}>
          <p style={{ marginLeft: 20 }} className="pageTitle">
            知识库分享
          </p>
          <div style={{ marginLeft: 20 }} className={styles.fromColumn}>
            <div className="zdyButtonA">
              <img
                style={{ cursor: 'pointer', position: 'relative', right: 8 }}
                onClick={this.enumeration}
                src={addShare}
              />
            </div>
          </div>
          {this.lessdata()}
        </div>
      </Suspense>
    );
  }
}

export default connect(({ user }) => ({
  currentUser: user.currentUser,
}))(Form.create()(KnowledgeBaseSharing));
